<template>
  <div style="padding: 10px; overflow-y: auto" v-loading="loading">
    <div class="header-btn">
      <div>{{ this.id ? '编辑' : '创建' }}海报</div>
      <div>
        <el-button type="primary" @click="confirm" :loading="loading">确认</el-button>
        <el-button type="info" plain @click="back">返回</el-button>
      </div>
    </div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="con">
          <div class="title">预览</div>
          <div class="view">
            <div id="view-con">
              <div class="viewcon" id="viewcon" ref="viewcon" style="width: 375px">
                <img class="contain" v-if="form.contentimg" :src="form.contentimg" ref="contentimg">
                <div span="8" class="left" v-if="form.codeUrl" @mousewheel.prevent="rollImg">
                  <img ref="imgDiv" @mousedown="move" class="box" style="width: 100px; height: 100px" :src="showQrCodeUrl"
                    alt="" crossorigin="anonymous" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="con">
          <div class="title">设置</div>
          <el-form ref="form" label-width="100px" label-position="right">
            <el-form-item label="名称" required>
              <el-input v-model="form.materialName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item :label="groupResolution" required>
              <el-select placeholder="请输入" v-model="form.categoryId" style="width: 100%">
                <el-option v-for="item in personGroup" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="图片" required>
              <el-upload class="avatar-uploader1" action :show-file-list="false" :before-upload="beforeUpload">
                <i v-if="!form.contentimg" class="el-icon-plus avatar-uploader-icon"></i>
                <el-image v-else style="width: 178px; height: 178px" fit="contain" :src="form.contentimg"></el-image>
              </el-upload>
              <span class="suggestion">建议上传750*1624像素的图片</span>
            </el-form-item>
            <el-form-item label="活码">
              <div class="block-wrap">
                <div class="block-item" @click="selectCode(1)">
                  <svg-icon icon-class="staff" />
                  <div>员工码</div>
                </div>
                <div class="block-item" @click="selectCode(2)">
                  <svg-icon icon-class="channel" />
                  <div>渠道活码</div>
                </div>
                <div class="block-item" @click="selectCode(3)">
                  <svg-icon icon-class="qunhuoma" />
                  <div>群活码</div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="其他设置" v-if="this.$route.query.is_person == 1">
              <el-checkbox v-model="form.isSyncToEnterprise" label="同步到企业海报库" :true-label="'1'" :false-label="'0'"></el-checkbox>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="codeType === 1 ? '选择员工活码' : codeType === 2 ? '选择渠道活码' : '选择群活码'" :visible.sync="codeVisible" width="620px" :before-close="handleClose" :close-on-click-modal="false">
      <div class="search">
        <el-input v-model="staffName" placeholder="员工名称" style="width: 250px" v-if="codeType == 1" @blur="getCustCode">
          <i slot="suffix" class="el-icon-search"></i>
        </el-input>
        <el-input v-model="staffName" placeholder="渠道活码名称" style="width: 250px" v-if="codeType == 2" @blur="verbalList">
          <i slot="suffix" class="el-icon-search"></i>
        </el-input>
        <el-input v-model="staffName" placeholder="群活码名称" style="width: 250px" v-if="codeType == 3" @blur="groupCode">
          <i slot="suffix" class="el-icon-search"></i>
        </el-input>
      </div>
      <el-table ref="multipleTable" :data="tableData" style="width: 100%" height="250" @select="handleSelectionChange" @select-all="selectAll">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column prop="activityName" label="二维码" align="center" v-if="codeType != 1" />
        <el-table-column prop="name" label="使用员工" align="center" v-if="codeType == 1" />
        <el-table-column prop="userNames" label="使用员工" align="center" v-if="codeType == 2" />
        <el-table-column prop="userNames" label="兜底员工" align="center" v-if="codeType == 2" />
        <el-table-column prop="userName" label="使用员工" align="center" v-if="codeType == 3" />
        <el-table-column prop="groupWays" label="拉群方式" align="center" v-if="codeType == 3" />
      </el-table>
      <NormalPagination :currentPage="page.pageNum" :pageSize="page.pageSize" :total="page.total" layout="total,sizes,prev,pager,next" :pagerCount="5" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" plain @click="handleClose">关 闭</el-button>
        <el-button type="primary" @click="determination">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getCustCode, groupCode, verbalList } from '@/api/operate/verbalTrick'
import html2canvas from 'html2canvas'
import { addMaterial, articleEdit, articleInfo, categoryList, uploadFile } from '@/api/article/group'
import { dateFormat } from '@/utils'

export default {
  props: {
    isCodeShow: {
      require: true,
      type: Boolean
    }
  },
  name: 'Edit',
  // components: { Tiny },
  data() {
    return {
      groupResolution: '个人分组',
      levelType: 1,
      codeType: 1, //1表示员工 2：渠道 3：群活码
      currentRow: '',
      codeVisible: false,
      staffName: '',
      domain: window.globalConfig.IMAGE_API,
      loading: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      tableData: [],
      codeUrl: '',
      id: '',
      rich: '',
      tags: '',
      tagVisible: false,
      personGroup: [],
      companyGroup: [],
      timeFlag: false,
      other: [],
      form: {
        coverUrl: '',
        materialName: '',
        author: '',
        codeUrl: '',
        articleCreateTime: '',
        contentimg: '',
        categoryId: '',
        levelId: '',
        levelType: '',
        content: '',
        materialUrl: '',
        digest: '',
        isSyncToEnterprise: '0',
        isAutoLabel: '0',
        materialTag: [],
        checkedGroupCode: ''
      },
      showQrCodeUrl: '',
    }
  },
  created() {
    // if (this.$route.query.levelType === 0) {
    //   this.groupResolution = '企业分组'
    // }
    this.init()
    console.log(this.$route.query)
    if (this.$route.query.hasOwnProperty('id')) {
      this.id = this.$route.query.id
      this.getInfo(this.id)
    }
  },
  methods: {
    // 拖动图片
    move(e) {
      console.log(e)
      e.preventDefault()
      // 获取元素
      var left = document.querySelector('.left')
      var img = document.querySelector('.box')
      var x = e.pageX - img.offsetLeft
      var y = e.pageY - img.offsetTop
      // 添加鼠标移动事件
      left.addEventListener('mousemove', move)

      function move(e) {
        img.style.left = e.pageX - x + 'px'
        img.style.top = e.pageY - y + 'px'
      }

      // 添加鼠标抬起事件，鼠标抬起，将事件移除
      img.addEventListener('mouseup', function () {
        left.removeEventListener('mousemove', move)
      })
      // 鼠标离开父级元素，把事件移除
      left.addEventListener('mouseout', function () {
        left.removeEventListener('mousemove', move)
      })
    },
    // 缩放图片
    rollImg() {
      /* 获取当前页面的缩放比 若未设置zoom缩放比，则为默认100%，即1，原图大小 */
      var zoom = parseInt(this.$refs.imgDiv.style.zoom) || 80
      /* event.wheelDelta 获取滚轮滚动值并将滚动值叠加给缩放比zoom wheelDelta统一为±120，其中正数表示为向上滚动，负数表示向下滚动 */
      zoom += event.wheelDelta / 5
      /* 最小范围 和 最大范围 的图片缩放尺度 */
      if (zoom >= 80 && zoom < 500) {
        this.$refs.imgDiv.style.zoom = zoom + '%'
      }
      return false
    },
    handleSizeChange(value) {
      this.page.pageNum = 1
      this.page.pageSize = value
      if (this.codeType === 3) {
        this.groupCode()
      } else if (this.codeType === 2) {
        this.verbalList(this.codeType)
      } else if (this.codeType === 1) {
        this.getCustCode()
      }
    },
    handleCurrentChange(value) {
      this.page.pageNum = value
      if (this.codeType === 3) {
        this.groupCode()
      } else if (this.codeType === 2) {
        this.verbalList(this.codeType)
      } else if (this.codeType === 1) {
        this.getCustCode()
      }
    },
    handleClose() {
      this.codeVisible = false
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0
      }
    },
    // 实现单选
    handleSelectionChange(val, row) {
      this.$refs.multipleTable.clearSelection() //清除选择
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.checkedGroupCode = row
      this.currentRow = row
    },
    determination() {
      if (this.form.contentimg) {
        if (this.codeType == 3) {
          this.form.codeUrl = this.checkedGroupCode.codeUrl
        } else {
          this.form.codeUrl = this.checkedGroupCode.qrCode
        }
        let str = this.form.codeUrl
        console.log('str',str);
        if (str.indexOf(window.globalConfig.WEXIN_QRCODE) !== -1) {
          this.showQrCodeUrl = window.globalConfig.SCRM_QRCODE + '/userQrCode' + this.form.codeUrl.substring(this.form.codeUrl.indexOf('?'))
        } else {
          this.showQrCodeUrl = this.form.codeUrl
        }
        this.handleClose()
      } else {
        this.handleClose()
        this.$message.error('请先上传海报')
      }
    },
    // 清除全选
    selectAll() {
      this.$refs.multipleTable.clearSelection() //清除选择
    },
    // 选择活码
    selectCode(type) {
      this.staffName = ''
      this.codeType = type
      if (this.codeType === 3) {
        this.groupCode(type)
      } else if (this.codeType === 2) {
        this.verbalList(type)
      } else if (this.codeType === 1) {
        this.getCustCode()
      } else {
        this.codeVisible = true
      }
    },
    groupCode() {
      const params = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        activityName: this.staffName || ''
      }
      groupCode(params).then((res) => {
        this.codeVisible = true
        this.tableData = res.rows || []
        this.page.total = res.total || 0
      })
    },
    getCustCode() {
      const params = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        name: this.staffName || ''
      }
      getCustCode(params).then((res) => {
        this.codeVisible = true
        this.tableData = res.rows || []
        this.page.total = res.total || 0
      })
    },
    verbalList(type) {
      const params = {
        levelType: type,
        mediaType: 1,
        tabsType: 0,
        activityName: this.staffName || '',
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
      }
      verbalList(params).then((res) => {
        this.codeVisible = true
        this.tableData = res.rows || []
        this.page.total = res.total || 0
      })
    },
    init() {
      if (this.$route.query.levelType === 0) {
        this.levelType = 0
      } else if (this.$route.query.levelType === 1) {
        this.levelType = 1
      }
      categoryList({ levelType: '1', mediaType: 5 }).then((res) => {
        if (res.code === 200) {
          const { data } = res
          this.personGroup = data
        }
      })
    },
    getInfo(id) {
      articleInfo(id).then((res) => {
        if (res.code === 200) {
          const { data } = res
          if (data.articleCreateTime) {
            this.timeFlag = true
          }
          this.form = {
            materialName: data.materialName,
            author: data.author || '',
            articleCreateTime: data.articleCreateTime
              ? new Date(data.articleCreateTime)
              : '',
            categoryId: data.categoryId,
            levelId: data.levelId,
            levelType: data.levelType,
            content: data.content,
            codeUrl: data.materialUrl,
            contentimg: this.domain + data.content,
            coverUrl: this.domain + data.coverUrl,
            materialUrl: data.materialUrl,

            // materialUrl: data.materialUrl,
            digest: data.digest,
            isSyncToEnterprise: data.isSyncToEnterprise == 0 ? '0' : '1',
            isAutoLabel: data.isAutoLabel == 0 ? '0' : '1',
            materialTag: data.materialTag ? data.materialTag.split('；') : []
          }

          if (this.form.codeUrl.indexOf(window.globalConfig.WEXIN_QRCODE) !== -1) {
            this.showQrCodeUrl = window.globalConfig.SCRM_QRCODE + '/userQrCode' + this.form.codeUrl.substring(this.form.codeUrl.indexOf('?'))
          } else {
            this.showQrCodeUrl = this.form.codeUrl
          }
          console.log(this.showQrCodeUrl, 'showQrcodeUrl', 'g')
        }
      })
    },
    confirm() {
      this.loading = true
      let this_ = this
      const img = new Image()
      img.src = this.form.contentimg
      img.onload = () => {
        // 获取原图尺寸， 根据宽度 计算出缩放比例
        let scale = img.width / 375
        scale = parseFloat(scale.toFixed(2))
        // 获取渲染出来的图片尺寸
        const width = parseInt(this_.$refs.viewcon.offsetWidth) * scale;
        const height = parseInt(this_.$refs.viewcon.offsetHeight) * scale;
        console.log(scale, 'scale', width, height)
        // 创建一个新的 canvas 元素，该 canvas 元素宽高与 原图保持一致
        const canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        console.log(canvas, 'canvas')
        console.log(this.$refs.viewcon,'viewCon')
        html2canvas(this.$refs.viewcon, {
          useCORS: true, // 支持图片跨域
          backgroundColor: null, // 画出来的图片有白色的边框,不要可设置背景为透明色（null）
          // scale: window.devicePixelRatio
          // width: canvas.width,
          // height: canvas.height,
          // canvas: canvas,
          scale: scale,
        }).then((canvas) => {
          this.form.coverUrl = canvas.toDataURL('image/png') //可将 canvas 转
          this.addArticle()
        }).catch(() => {})
      }
    },

    addArticle() {
      this.loading = false
      console.log('进入到这个方法')
      if (this.form.materialName == '') {
        return this.$message.error('请输入名称')
      }
      if (this.form.categoryId == '') {
        return this.$message.error('请选择个人分组')
      }
      if (this.form.contentimg == '') {
        return this.$message.error('请选择图片')
      }
      console.log('form', this.form)
      this.loading = true
      if (this.id) {
        if (this.$route.query.levelType = 0) {
          articleEdit({
            id: this.id,
            categoryId: this.form.categoryId,
            materialUrl: this.form.materialUrl,
            materialName: this.form.materialName,
            digest: this.form.digest,
            content: this.form.content,
            coverUrl: this.form.coverUrl,
            codeUrl: this.form.codeUrl,
            levelId: this.form.levelId,
            levelType: this.form.levelType,
            author: this.form.author,
            materialTag: this.form.materialTag.join('；'),
            mediaType: '5',
            articleCreateTime: this.timeFlag ? dateFormat(this.form.articleCreateTime) : null,
            isSyncToEnterprise: this.form.isSyncToEnterprise,
            isAutoLabel: this.form.isAutoLabel
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.back()
            }
          }).finally(() => {
            this.loading = false
          })
        } else {
          articleEdit({
            id: this.id,
            categoryId: this.form.categoryId,
            materialUrl: this.form.materialUrl,
            materialName: this.form.materialName,
            digest: this.form.digest,
            content: this.form.content,
            coverUrl: this.form.coverUrl,
            codeUrl: this.form.codeUrl,
            levelId: this.form.levelId,
            levelType: this.form.levelType,
            author: this.form.author,
            materialTag: this.form.materialTag.join('；'),
            mediaType: '5',
            articleCreateTime: this.timeFlag ? dateFormat(this.form.articleCreateTime) : null,
            isSyncToEnterprise: this.form.isSyncToEnterprise,
            isAutoLabel: this.form.isAutoLabel
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.back()
            }
          }).finally(() => {
            this.loading = false
          })
        }
      } else {
        addMaterial({
          categoryId: this.form.categoryId,
          materialUrl: this.form.materialUrl,
          materialName: this.form.materialName,
          digest: this.form.digest,
          content: this.form.content,
          coverUrl: this.form.coverUrl,
          codeUrl: this.form.codeUrl,
          levelId: this.form.levelId,
          levelType: '1',
          author: this.form.author,
          materialTag: this.form.materialTag.join('；'),
          mediaType: '5',
          articleCreateTime: this.timeFlag
            ? dateFormat(this.form.articleCreateTime)
            : null,
          isSyncToEnterprise: this.form.isSyncToEnterprise,
          isAutoLabel: this.form.isAutoLabel
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.back()
          }
        })
          .finally(() => {
            this.loading = false
          })
      }
    },
    beforeUpload(data) {
      const formData = new FormData()
      formData.append('file', data)
      uploadFile(formData).then((res) => {
        if (res.code === 200) {
          this.form.contentimg = this.domain + res.data.url
          // this.form.contentimg = '/orginImage/%E6%B5%8B%E8%AF%95%E5%9B%BE%E7%89%87.png'
          this.form.content = res.data.url
        }
      })
      return false
    },
    addTag() {
      this.tags = this.form.materialTag.join('；')
      this.tagVisible = true
    },
    handleCloseTag(tag) {
      this.form.materialTag.splice(this.form.materialTag.indexOf(tag), 1)
    },
    back() {
      this.$router.push({
        name: 'Poster',
        query: { is_person: this.$route.query.is_person }
      })
    },
    download() {
      const imgUrl =
        'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
      const a = document.createElement('a')
      fetch(imgUrl)
        .then((res) => res.blob())
        .then((blob) => {
          a.href = URL.createObjectURL(blob)
          a.download = '123.jpg'
          document.body.appendChild(a)
          a.click()
          window.URL.revokeObjectURL(a.href)
          document.body.removeChild(a)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.header-btn {
  @include headerBtn;
}

.header {
  font-size: 20px;
  padding: 10px 0;

  .btn-con {
    float: right;
  }
}

.suggestion {
  font-size: 12px;
  color: #d2d2d2;
}

.con {
  background-color: #fff;
  border-radius: 3px;
  padding-bottom: 16px;
  //overflow: hidden;
  min-height: 706px;

  .title {
    position: relative;
    height: 55px;
    line-height: 55px;
    font-size: 18px;
    border-bottom: 1px solid #f7f7f7;
    box-sizing: border-box;
    padding-left: 20px;

    &::before {
      content: "";
      display: block;
      position: absolute;
      width: 3px;
      height: 20px;
      background-color: #082aff;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .view {
    display: flex;
    justify-content: center;
    #view-con {
      position: relative;
      background-color: #fff;
      float: left;
      overflow: hidden;
      box-sizing: border-box;
      width: 375px;
      //background: url(../../../assets/image/image2.jpg) no-repeat;
      background-size: cover;
      //padding: 9px;
      display: flex;
      align-items: center;
      margin-top: 20px;
      padding: 0;
      font-size: 0px;
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep {
  .avatar-uploader1 .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader1 .el-upload:hover {
    border-color: #409eff;
  }
}

@import "@/styles/base.scss";

.block-wrap {
  margin-left: -10px;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  font-weight: 400;
  color: #2a2a2a;
  font-size: 12px;
  font-family: PingFangSC-Medium, PingFang SC;

  .block-item {
    width: 80px;
    padding: 5px 0;
    margin: 10px;
    border: $normalBorder;
    text-align: center;

    .svg-icon {
      width: 4em;
      height: 3em;
      vertical-align: -0.15em;
      fill: currentColor;
      overflow: hidden;
      margin-top: 12px;
    }

    div {
      margin-top: -10px;
    }
  }
}

.search {
  margin-bottom: 10px;
}

.table-page {
  text-align: right;
  height: 40px;
  margin-top: 15px;
}

.box {
  position: absolute;
  top: 250px;
  left: 100px;
  width: 100%;
  height: 100%;
  max-width: 923px;
  max-height: 460px;
  cursor: move;
}

.contain{
  //height: 525px !important;
  width: 375px;
  padding: 0;
  margin: 0;
  //margin-left: 12px;
  //overflow: hidden;
  display: block;
}
</style>
